package stream_hub

import (
	"bytes"
	"encoding/json"
	"errors"
	"github.com/tidwall/gjson"
	"io/ioutil"
	"net/http"
	"net/url"
	"vrcm/src/vrcm/app/admin/models"
	dto "vrcm/src/vrcm/app/admin/service/dto/stream_hub"
	"vrcm/src/vrcm/app/admin/service/ngvsa"
	ext "vrcm/src/vrcm/envconfig"
)

func (e *StreamHubService) CreateWatermarkTask(d *dto.CreateWatermarkTaskReq) (*dto.CreateWatermarkTaskRes, error) {
	ngvsaService := ngvsa.NgvsaService{}
	ngvsaService.Log = e.Log
	streamHubUrl, err := ngvsaService.GetStreamHubInfo(d.TenantId, "tenant", "station")
	if err != nil {
		e.Log.Errorf("获取streamHubUrl失败 error:%s", err)
		return nil, err
	}

	res := &dto.CreateWatermarkTaskRes{}
	params := url.Values{}
	urlString := streamHubUrl + "/v1/mediatranscoder_watermark/stream"
	Url, err := url.Parse(urlString)
	if err != nil {
		return nil, err
	}
	params.Set("tenantId", d.TenantId)
	Url.RawQuery = params.Encode()
	urlPath := Url.String()
	e.Log.Trace("CreateWatermarkTask:", urlPath)
	// 参数
	data := make(map[string]interface{})
	data["name"] = d.Name
	data["input"] = d.Input
	data["type"] = d.Type
	data["output"] = d.Output
	data["callbackAddress"] = d.CallbackAddress
	data["ngvsaServiceUrl"] = d.NgvsaServiceUrl
	data["vrcServiceUrl"] = d.VrcServiceUrl
	// Marshal
	bytesData, _ := json.Marshal(data)
	e.Log.Trace(string(bytesData))
	// 获取 request请求
	request, err := http.NewRequest("POST", urlPath, bytes.NewReader(bytesData))
	if len(ext.ExtConfig.ServiceConfig.VsApiServiceUrl) > 0 {
		request.Header.Set("Authorization", "Bearer "+models.SuperToken)
		request.Header.Set("X-PS-Flag", "")
	} else {
		request.Header.Set("Authorization", "vsnb")
	}
	request.Header.Add("Content-Type", "application/json")
	if err != nil {
		e.Log.Errorf("GetHttpSkip Request Error:", err)
		return nil, err
	}
	response, err := client.Do(request)
	if err != nil {
		e.Log.Errorf("GetHttpSkip Response Error:", err)
		return nil, err
	}
	defer response.Body.Close()
	body, err := ioutil.ReadAll(response.Body)
	if err != nil {
		e.Log.Errorf("读取响应体失败 error:%s", err)
		return res, err
	}
	e.Log.Trace("CreateWatermarkTask:", string(body))
	result := gjson.Parse(string(body))
	if result.Get("code").Int() != http.StatusOK {
		return res, errors.New(result.Get("message").String())
	}

	err = json.Unmarshal([]byte(result.Get("data").String()), res)
	if err != nil {
		e.Log.Errorf("读取响应体失败 error:%s", err)
		return res, err
	}
	return res, nil
}

func (e *StreamHubService) DeleteWatermarkTask(d *dto.DeleteWatermarkTaskReq) error {
	ngvsaService := ngvsa.NgvsaService{}
	ngvsaService.Log = e.Log
	streamHubUrl, err := ngvsaService.GetStreamHubInfo(d.TenantId, "tenant", "station")
	if err != nil {
		e.Log.Errorf("获取streamHubUrl失败 error:%s", err)
		return err
	}

	params := url.Values{}
	urlString := streamHubUrl + "/v1/mediatranscoder_watermark/stream/" + d.TaskId
	Url, err := url.Parse(urlString)
	if err != nil {
		return err
	}
	params.Set("tenantId", d.TenantId)
	Url.RawQuery = params.Encode()
	urlPath := Url.String()
	e.Log.Trace("DeleteWatermarkTask:", urlPath)

	request, err := http.NewRequest("DELETE", urlPath, nil)
	if len(ext.ExtConfig.ServiceConfig.VsApiServiceUrl) > 0 {
		request.Header.Set("Authorization", "Bearer "+models.SuperToken)
		request.Header.Set("X-PS-Flag", "")
	} else {
		request.Header.Set("Authorization", "vsnb")
	}
	request.Header.Add("Content-Type", "application/json")
	if err != nil {
		e.Log.Errorf("GetHttpSkip Request Error:", err)
		return err
	}
	response, err := client.Do(request)
	if err != nil {
		e.Log.Errorf("GetHttpSkip Response Error:", err)
		return err
	}

	defer response.Body.Close()
	body, err := ioutil.ReadAll(response.Body)
	if err != nil {
		e.Log.Errorf("读取响应体失败 error:%s", err)
		return err
	}
	e.Log.Trace("DeleteWatermarkTask:", string(body))
	result := gjson.Parse(string(body))

	if result.Get("code").Int() != http.StatusOK {
		return errors.New(result.Get("message").String())
	}
	return nil
}

func (e *StreamHubService) StartWatermarkTask(d *dto.StartWatermarkTaskReq) error {
	ngvsaService := ngvsa.NgvsaService{}
	ngvsaService.Log = e.Log
	streamHubUrl, err := ngvsaService.GetStreamHubInfo(d.TenantId, "tenant", "station")
	if err != nil {
		e.Log.Errorf("获取streamHubUrl失败 error:%s", err)
		return err
	}

	params := url.Values{}
	urlString := streamHubUrl + "/v1/mediatranscoder_watermark/stream/" + d.TaskId + "/start"
	Url, err := url.Parse(urlString)
	if err != nil {
		return err
	}
	params.Set("tenantId", d.TenantId)
	Url.RawQuery = params.Encode()
	urlPath := Url.String()
	e.Log.Trace("StartWatermarkTaskReq:", urlPath)

	request, err := http.NewRequest("PUT", urlPath, nil)
	if len(ext.ExtConfig.ServiceConfig.VsApiServiceUrl) > 0 {
		request.Header.Set("Authorization", "Bearer "+models.SuperToken)
		request.Header.Set("X-PS-Flag", "")
	} else {
		request.Header.Set("Authorization", "vsnb")
	}
	request.Header.Add("Content-Type", "application/json")
	if err != nil {
		e.Log.Errorf("GetHttpSkip Request Error:", err)
		return err
	}
	response, err := client.Do(request)
	if err != nil {
		e.Log.Errorf("GetHttpSkip Response Error:", err)
		return err
	}

	defer response.Body.Close()
	body, err := ioutil.ReadAll(response.Body)
	if err != nil {
		e.Log.Errorf("读取响应体失败 error:%s", err)
		return err
	}
	e.Log.Trace("StartWatermarkTaskReq:", string(body))
	result := gjson.Parse(string(body))

	if result.Get("code").Int() != http.StatusOK {
		return errors.New(result.Get("message").String())
	}
	return nil
}

func (e *StreamHubService) StopWatermarkTask(d *dto.StopWatermarkTaskReq) error {
	ngvsaService := ngvsa.NgvsaService{}
	ngvsaService.Log = e.Log
	streamHubUrl, err := ngvsaService.GetStreamHubInfo(d.TenantId, "tenant", "station")
	if err != nil {
		e.Log.Errorf("获取streamHubUrl失败 error:%s", err)
		return err
	}

	params := url.Values{}
	urlString := streamHubUrl + "/v1/mediatranscoder_watermark/stream/" + d.TaskId + "/stop"
	Url, err := url.Parse(urlString)
	if err != nil {
		return err
	}
	params.Set("tenantId", d.TenantId)
	Url.RawQuery = params.Encode()
	urlPath := Url.String()
	e.Log.Trace("StopWatermarkTask:", urlPath)

	request, err := http.NewRequest("PUT", urlPath, nil)
	if len(ext.ExtConfig.ServiceConfig.VsApiServiceUrl) > 0 {
		request.Header.Set("Authorization", "Bearer "+models.SuperToken)
		request.Header.Set("X-PS-Flag", "")
	} else {
		request.Header.Set("Authorization", "vsnb")
	}
	request.Header.Add("Content-Type", "application/json")
	if err != nil {
		e.Log.Errorf("GetHttpSkip Request Error:", err)
		return err
	}
	response, err := client.Do(request)
	if err != nil {
		e.Log.Errorf("GetHttpSkip Response Error:", err)
		return err
	}

	defer response.Body.Close()
	body, err := ioutil.ReadAll(response.Body)
	if err != nil {
		e.Log.Errorf("读取响应体失败 error:%s", err)
		return err
	}
	e.Log.Trace("StopWatermarkTask:", string(body))
	result := gjson.Parse(string(body))

	if result.Get("code").Int() != http.StatusOK && result.Get("code").Int() != 10000016 && result.Get("code").Int() != 404 {
		return errors.New(result.Get("message").String())
	}
	return nil
}

// RemoveWatermarkTask 删除转码任务
func (e *StreamHubService) RemoveWatermarkTask(d *dto.RemoveWatermarkTaskReq) error {

	err := e.StopWatermarkTask(&dto.StopWatermarkTaskReq{TaskId: d.TaskId, TenantId: d.TenantId})
	if err != nil {
		e.Log.Errorf("StopWatermarkTaskReq失败 error:%s", err)
		return err
	}
	err = e.DeleteWatermarkTask(&dto.DeleteWatermarkTaskReq{TaskId: d.TaskId, TenantId: d.TenantId})
	if err != nil {
		e.Log.Errorf("DeleteWatermarkTask失败 error:%s", err)
		return err
	}
	return nil
}
